import { findFilterItemByName } from './util'

const handlers = {
  search() {
    this.submit()
  },
  back() {
    var item = null

    if (this.targetValue) {
      item = findFilterItemByName(this.target, this.targetValue)
    }

    this.input = ''
    this.targetValue = ''

    if (item) {
      this.selectFilterValue(item.value)
      this.clearTargetFilter()
      // 移动输入框到筛选器列表的末尾
      this.$tokens.append(this.$inputDropdown)
    } else {
      this.clearTargetFilter()
    }
    this.$input.focus()
  },
  apply(paramsStr) {
    const params = JSON.parse(unescape(paramsStr))
    this.active = true
    this.setData(params)
    this.commit()
  },
  'clear-history': function () {
    this.history.clear()
    this.buildInputDropdown()
  }
}

export function exec(_this, cmd) {
  const i = cmd.indexOf('<cmd:')

  if (i < 0) {
    return false
  }

  const [name, params] = cmd.slice(i + 5, -1).split(':')

  if (handlers[name]) {
    handlers[name].call(_this, params)
    return true
  }
  return false
}

export default null
